package com.cxyzy.demo

import com.cxyzy.demo.SPUtil.getTokenFromSP
import com.cxyzy.demo.request.LoginReq
import com.cxyzy.demo.response.BaseResp
import com.cxyzy.demo.response.EmptyResp
import com.cxyzy.demo.response.LoginResp


object LoginManager {
    fun getLoginToken() = getTokenFromSP()

    private fun saveLoginInfo(loginId: String, password: String, resp: LoginResp) {
        SPUtil.saveLoginIdInSP(loginId)
        SPUtil.saveLoginPassInSP(password)
        SPUtil.saveLoginRespInSP(resp)
    }

    fun login(onSuccess: ((resp: LoginResp) -> Unit)? = null,
              onFailure: ((resp: BaseResp<EmptyResp>) -> Unit)? = null) {
        val loginId = SPUtil.getLoginIdFromSP()
        val password = SPUtil.getLoginPassFromSP()
        if (loginId.isNullOrEmpty() || password.isNullOrEmpty()) {
            return
        }

        val call = HttpRepository.login(LoginReq(loginId, password))
        val response = call.execute()

        response.body()?.data?.let {
            saveLoginInfo(loginId, password, it)
            onSuccess?.invoke(it)
            return
        }
        onFailure?.invoke(BaseResp(message = response.body()?.message))
    }


}